use std::fs;
use pest::Parser;

use crate::grammar::{LangParser, Rule};
use crate::error_scan::{scan_all_index_errors, report_pest_error};
use crate::pretty::format_program;

pub fn run(path: &str) -> ! {
    let src = match fs::read_to_string(path) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("读取失败 {path}: {e}");
            std::process::exit(1);
        }
    };

    // A) 先行级错误扫描
    let msgs = scan_all_index_errors(&src);
    if !msgs.is_empty() {
        for m in msgs {
            eprintln!("{m}");
        }
        std::process::exit(1);
    }

    // B) pest 解析
    match LangParser::parse(Rule::program, &src) {
        Ok(mut pairs) => {
            let program = pairs.next().unwrap();
            let formatted = format_program(program);

            // 去掉末尾多余换行
            let trimmed = formatted.trim_end_matches('\n');

            // 用 eprint!，最后只输出一个换行，不会多
            println!("{trimmed}\n");
            std::process::exit(0);
        }
        Err(err) => {
            report_pest_error(err, &src);
            std::process::exit(1);
        }
    }
}
